<?php
$root = $_SERVER['DOCUMENT_ROOT'];
if ( file_exists( $root.'/wp-load.php' ) ) {
    require_once( $root.'/wp-load.php' );
} elseif ( file_exists( $root.'/wp-config.php' ) ) {
    require_once( $root.'/wp-config.php' );
}

$sections = array();
foreach ($echotheme_options as $key => $value) {
	if (is_array($value)) {
		$sections[] = $key;
	}
}
// var_dump($echotheme_options);
header("Content-type: text/javascript");
?>
jQuery(document).ready(function($) {
<?php
	foreach ($sections as $section) :
?>
// <?php echo ucfirst($section) ?> Background Image
$('#upload_<?php echo $section ?>_background-image_button').click(function() {
    formfield = $('#<?php echo $section; ?>_background-image').attr('id');
    tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
    return false;
});
<?php
	endforeach;
?>    
        // used for all of the above to insert the uploaded image url into the proper text field
	window.send_to_editor = function(html) {
	    imgurl = $('img',html).attr('src');
	    $('#'+ formfield).val(imgurl);
	    tb_remove();
	}
});

jQuery(document).ready(function($) {
	
<?php 
foreach ($sections as $section) :
?>
if ( $('#<?php echo $section ?>BGcolorSelector').length == 1 ) { // if element found
addUploader('#<?php echo $section; ?>_background-color', '#<?php echo $section; ?>BGcolorSelector', rgb2hex( $('#<?php echo $section; ?>BGcolorSelector div').css('background-color') ));
}

if ( $('#<?php echo $section ?>TextColor').length == 1 ) { // if element found
addUploader('#<?php echo $section; ?>_color', '#<?php echo $section; ?>TextColor', rgb2hex( $('#<?php echo $section; ?>TextColor div').css('background-color') ));
}
<?php
endforeach; 
?>
	
	function addUploader(inputField, colorSelector, defaultColor) {
	$(colorSelector).ColorPicker({
		color: '#'+defaultColor,
		onShow: function (colpkr) {
			$(colpkr).fadeIn(500);
			return false;
		},
		onHide: function (colpkr) {
			$(colpkr).fadeOut(500);
			return false;
		},
		onChange: function (hsb, hex, rgb) {
			$(colorSelector+' div').css('backgroundColor', '#' + hex);
			$('input'+inputField).attr("value", hex);
		},
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).val(hex);
			$(el).ColorPickerHide();
		}
	});
    }
    // convert rgb to hex color string
    function rgb2hex(rgb) {
	if (  rgb.search("rgb") == -1 ) {
	    return rgb;
	} else {
	    rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
	    function hex(x) {
		return ("0" + parseInt(x).toString(16)).slice(-2);
	    }
	    return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
	}
    }
});